<script lang="ts" setup>
import { getCourseInformationById, getFolderInfoApi, getSourceFileUrlApi } from '@/api/study/course';
import type { CourseFileType, SourceFileType } from '@/api/types/courseTypes';
import { validateNull } from '@/utils/validate';
import { type ItemType, message } from 'ant-design-vue';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

const props = defineProps<{
  folderId: string;
  courseId: string;
}>();
const router = useRouter();
const folderInfo = ref<CourseFileType | null>(null);
const courseName = ref<string>('');

// 获取该课程的层级目录关系
// 获取课程目录信息
const fetchFolderInfo = async () => {
  try {
    const response = await getFolderInfoApi(props.folderId);
    folderInfo.value = response;
  }
  catch (error) {
    message.error("获取课程目录信息失败")
  }
}

// 获取课程标题名称
const fetchCourseName = async () => {
  try {
    const response = await getCourseInformationById(props.courseId);
    courseName.value = response.courseName;
  }
  catch (error) {
    message.error("获取课程元信息失败")
  }
};

// 递归生成菜单项
const generateMenuItems = (files: CourseFileType[]): ItemType[] => {
  return files.map((file) => {
    const children = file.childFiles
      ? generateMenuItems(file.childFiles)
      : file.sourceFiles.map(source => ({
        key: source.sourceId,
        label: source.name,
      }));

    return {
      key: file.courseFileId,
      label: file.name,
      ...(children.length > 0 ? { children } : {}),
    };
  });
};

const handleMenuClick = async (clickEvent: any) => {
  const sourceId = clickEvent.key;

  // 利用深度搜索folderInfo中sourceFiles字段 找到对应的sourceId，根据tag字段判断类型 tag = 文档 || 网页资源 || 音视频
  const findSourceFile = (files: CourseFileType[], sourceId: string): SourceFileType | null => {
    for (const file of files) {
      if (!validateNull(file.sourceFiles)) {
        for (const source of file.sourceFiles) {
          if (source.sourceId === sourceId)
            return source;
        }
      }

      if (!validateNull(file.childFiles)) {
        const found = findSourceFile(file.childFiles, sourceId);
        if (!validateNull(found))
          return found;
      }
    }
    return null;
  };

  const selectedSourceFile = folderInfo.value ? findSourceFile(folderInfo.value.childFiles, sourceId) : null as SourceFileType | null;
  if (!validateNull(selectedSourceFile)) {
    const filePath = selectedSourceFile?.sourcePath ?? '';
    if (filePath === '') {
      message.error("文件路径为空，无法继续操作");
      return;
    }

    if (selectedSourceFile?.tag === '文档') {
      router.push({
        name: 'DocumentViewer',
        params: {
          courseId: props.courseId,
          folderId: props.folderId,
          sourceId,
          filePath,
        },
      });
    }
    else if (selectedSourceFile?.tag === '网页资源') {
      try {
        const webUrl = await getSourceFileUrlApi(sourceId);
        window.open(webUrl as string, '_blank');
      }
      catch (error) {
        message.error("获取网页资源失败");
      }
    }
    else if (selectedSourceFile?.tag === '音视频') {
      router.push({
        name: 'video',
        params: {
          courseId: props.courseId,
          folderId: props.folderId,
          sourceId,
          filePath,
        },
      });
    }
  }
  else {
    message.error("未找到对应的文件资源");
  }
};

onMounted(() => {
  fetchFolderInfo();
  fetchCourseName();
});
</script>

<template>
  <div class="sidebar">
    <div class="logo">
      <img src="/1.png" alt="平台LOGO" class="logo-img">
      <h1 class="title">
        {{ courseName }}
      </h1>
    </div>
    <a-menu mode="inline" :items="folderInfo ? generateMenuItems(folderInfo.childFiles) : []" @click="handleMenuClick" />
  </div>
</template>

<style scoped>
.sidebar {
  width: 100%;
  height: 100vh;
}

.logo {
  display: flex;
  align-items: center;
  padding: 16px;
}

.logo-img {
  width: 40px;
  height: 40px;
  margin-right: 16px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.a-menu {
  background-color: #001529;
  color: #fff;
}
</style>
